package com.shuimin.group.mid.time;

import com.shuimin.group.mid.chat.ChatEvent;
import com.shuimin.group.mid.chat.ChatService;
import pond.common.JSON;
import pond.common.S;
import pond.web.WSCtx;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Task_KeepAlive extends  TimerTask{
    private WSCtx wsCtx = null;
    public Task_KeepAlive(WSCtx wsCtx) {
        wsCtx = wsCtx;
    };
    ScheduledFuture<?> future = null;
    public Task_KeepAlive start(ScheduledExecutorService keepAliveTimer){

        future = keepAliveTimer.scheduleAtFixedRate(
                this,
                1,
                60,
                TimeUnit.SECONDS
        );
        return this;
    }
    @Override
    public void run() {
        if (wsCtx != null && wsCtx.context.channel().isOpen()) {
            wsCtx.sendTextFrame(JSON.stringify(ChatEvent.keepAlive()));
        } else {
            S.echo("wsCtx dead, cancel TimerTask_keepAlive");
            if (future != null)
            {
                future.cancel(false);
            }
        }
    }
}
